package graph;

import java.io.File;
import java.util.Set;

import mapreduce.Task;

public class EdgesBuilder {
	MyTimer timer = new MyTimer();
	File m_idAssignResultFile = new File("id.assign.result");

	public DirectedEdges build(File dataFile, File edgesDir, EdgesConfig config) {
		if (!edgesDir.exists()) {
			edgesDir.mkdirs();
		}

		// 1. assign ids for users and tweets
		System.out.println("assigning id......");
		Task assignIdTask = AssignIdTask.getTask(1, dataFile,
				config.m_firstName, config.m_secondName, m_idAssignResultFile);
		assignIdTask.run();

		// 2. build id managers
		System.out.println("building id managers......");
		IdManager firstIdManager = IdManager.getIdManager(edgesDir.toString(),
				config.m_firstName);
		firstIdManager.load(getIDFile(config.m_firstName));
		IdManager secondIdManager = IdManager.getIdManager(edgesDir.toString(),
				config.m_secondName);
		secondIdManager.load(getIDFile(config.m_secondName));

		// 3. build edges data
		System.out.println("building edges data......");
		BuildMapTask buildMapTask = BuildMapTask.getTask(2, m_idAssignResultFile,
				config.m_relationName);
		buildMapTask.run();

		// 4. build Edges
		System.out.println("building edges db......");
		DbEdgesImplFactory factory = new DbEdgesImplFactory(edgesDir.toString());
		DirectedEdges edges = new DirectedEdges(factory, config.m_relationName);
		edges.load(BuildMapTask.getRelationFile(config.m_relationName,
				RelationDirection.DIRECT), BuildMapTask.getRelationFile(
				config.m_relationName, RelationDirection.INVERSE));
		
		// 5. release
		clean();

		System.out.println("TOTAL TIME:"
				+ new Integer((int) (timer.now() * .001)).toString());
		return edges;
	}

	private void clean() {
		// TODO Auto-generated method stub

	}

	/**
	 * get ID file from object name
	 * 
	 * @param name
	 * @return
	 */
	private File getIDFile(String name) {
		return new File(name + ".id");
	}

	public static void main(String[] args) {
		File dataFile = new File("../data/testFavFile.txt");
		File edgesDir = new File("../data/graph");
		EdgesBuilder builder = new EdgesBuilder();
		EdgesConfig config = new EdgesConfig("user", "tweets", "favorite");
		DirectedEdges edges = builder.build(dataFile, edgesDir, config);
		//test
		IdManager firstIdManager = IdManager.getIdManager(edgesDir.toString(), "user");
		IdManager secondIdManager = IdManager.getIdManager(edgesDir.toString(), "tweets");
		Set<Edge> edges0 = edges.getEdgesFrom(firstIdManager.getId("brechin"));
		for(Edge edge: edges0){
			System.out.println(secondIdManager.getText(edge.m_desId));
		}
		System.out.println("------------");
		edges0 = edges.getEdgesTo(secondIdManager.getId("2586943277"));
		for(Edge edge: edges0){
			System.out.println(firstIdManager.getText(edge.m_srcId));
		}
		System.out.println();
	}
}
